<template>
  <view class="normal-login-container">
    <view class="logo-content">
      <!-- <view class="logo-wrap">
      	<image style="width: 120rpx;height: 120rpx;" :src="globalConfig.appInfo.logo" mode="widthFix"></image>
      </view> -->
      <view class="margin-top">泰寓</view>
    </view>
    <view class="login-form-content">
      <!-- <button open-type="getRealtimePhoneNumber" @getRealtimePhoneNumber="handleLogin" class="login-btn cu-btn block bg-blue lg round">手机号快捷登录</button> -->
      <button open-type="getPhoneNumber" @getphonenumber="handleLogin" class="login-btn cu-btn block bg-blue lg round">手机号快捷登录</button>
      <button @click="accountLogin" class="login-btn cu-btn block bg-blue lg round">账号登录</button>
      <!-- <view class="xieyi text-center">
        <text class="text-grey1">登录即代表同意</text>
        <text @click="handleUserAgrement" class="text-blue">《用户协议》</text>
        <text @click="handlePrivacy" class="text-blue">《隐私协议》</text>
      </view> -->
		<!-- <view class="mine-info flex-ct-y">
		    <view class="photo">
				<image :src="userInfo.avatar" class="pic-cover" mode="aspectFill"></image>
				<button style="width: 100px;" type="balanced" open-type="chooseAvatar" @chooseavatar="chooseavatar">huoqu</button>
		    </view>
		    <input class="nickname" type="nickname" style="font-size:42rpx;" :value="userInfo.name"
					@input="nameInput" @blur="nameInput" />
		</view> -->
      <!-- <view class="input-item flex align-center">
        <view class="iconfont icon-user icon"></view>
        <input v-model="loginForm.username" class="input" type="text" placeholder="请输入账号" maxlength="30" />
      </view>
      <view class="input-item flex align-center">
        <view class="iconfont icon-password icon"></view>
        <input v-model="loginForm.password" type="password" class="input" placeholder="请输入密码" maxlength="20" />
      </view>
      <view class="input-item flex align-center" style="width: 60%;margin: 0px;" v-if="captchaEnabled">
        <view class="iconfont icon-code icon"></view>
        <input v-model="loginForm.code" type="number" class="input" placeholder="请输入验证码" maxlength="4" />
        <view class="login-code"> 
          <image :src="codeUrl" @click="getCode" class="login-code-img"></image>
        </view>
      </view>
      <view class="action-btn">
        <button @click="handleLogin" class="login-btn cu-btn block bg-blue lg round">登录</button>
      </view>
      <view class="reg text-center" v-if="register">
        <text class="text-grey1">没有账号？</text>
        <text @click="handleUserRegister" class="text-blue">立即注册</text>
      </view> -->
	  <!-- <view class="login-btn-bar">
		  <u-button type="primary" shape="circle" size="medium" @click="handleToPhoneLogin">手机号安全登陆</u-button>
		  <u-button :customStyle="{'margin-top': '60rpx'}" type="success" shape="circle" size="medium">一键登陆</u-button>
	  </view> -->
	  <!-- <view class="margin-top">
	  	<u-checkbox v-model="checked" shape="circle" >
		  <view class="xieyi text-center">
			<text class="text-grey1">我已阅读并同意</text>
			<text @click="handleUserAgrement" class="text-blue">《用户协议》</text>
			<text @click="handlePrivacy" class="text-blue">《隐私协议》</text>
		  </view>
	  	</u-checkbox>
	  </view> -->
	  
    </view>
     
  </view>
</template>

<script>
  import { getCodeImg, greet, checkBindWechat, bindWechat, loginByWechatPhone } from '@/api/login'
  const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

  export default {
    data() {
      return {
	    avatarUrl: defaultAvatarUrl,
        codeUrl: "",
        captchaEnabled: true,
		checked: false,
        // 用户注册开关
        register: false,
        globalConfig: getApp().globalData.config,
        loginForm: {
          username: "",
          password: "",
          code: "",
          uuid: ''
        },
		userInfo: {
			avatar: defaultAvatarUrl,
			name: ''
		},
        isLoggingIn: false, // 添加登录状态控制
      }
    },
    created() {
      this.getCode()
    },
    methods: {
	  chooseavatar(e) {	
	      // let avatarUrl = e.detail.avatarUrl
	      let avatarUrl = 'data:image/jpeg;base64,' +   uni.getFileSystemManager().readFileSync(e.detail.avatarUrl,'base64')
	  
	      uni.setStorageSync('avatarUrl', avatarUrl);
	      this.userInfo.avatar = avatarUrl
	      let data = {
	              name: this.userInfo.name,
	              avatar: avatarUrl
	      }
	      // getUserInfo(data).then(res => {}).catch(err => {})
	  
	  },
	  // 去手机号登陆
	  handleToPhoneLogin() {
		  this.$tab.navigateTo(`/pages/loginForPhone`)
	  },
      // 用户注册
      handleUserRegister() {
        this.$tab.redirectTo(`/pages/register`)
      },
      // 隐私协议
      handlePrivacy() {
        let site = this.globalConfig.appInfo.agreements[0]
        this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
      },
      // 用户协议
      handleUserAgrement() {
        let site = this.globalConfig.appInfo.agreements[1]
        this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
      },
      // 获取图形验证码
      getCode() {
        getCodeImg().then(res => {
          this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
          if (this.captchaEnabled) {
            this.codeUrl = 'data:image/gif;base64,' + res.img
            this.loginForm.uuid = res.uuid
          }
        })
      },
      // 去账号登录页面
      async accountLogin() {
        this.$tab.reLaunch('/pages/accountLogin');
      },
	    // 微信登录
      async handleLogin(e) {
        // 检查隐私协议是否同意
        // if (!this.checked) {
        //   uni.showToast({
        //     title: '请先同意用户协议和隐私政策',
        //     icon: 'none'
        //   })
        //   return
        // }

        // 防止重复点击
        if (this.isLoggingIn) return
        this.isLoggingIn = true

        try {
          console.log('登录信息:', e)
          const { code, errMsg } = e.detail
          
          if (errMsg !== "getPhoneNumber:ok") {
            throw new Error(errMsg || '获取手机号失败')
          }

          // 微信登录获取code
          const wxLoginRes = await this.wxLogin()
          if (!wxLoginRes.code) {
            throw new Error('微信登录失败')
          }

          // 获取openid
          const greetRes = await greet(wxLoginRes.code)
          if (!greetRes?.data?.openid) {
            throw new Error('获取openid失败')
          }

          const openid = greetRes.data.openid

          // 获取手机号
          const phoneRes = await loginByWechatPhone(code, openid)
          if (!phoneRes) {
            throw new Error('获取手机号信息失败')
          }

          // 执行微信登录
          await this.wechatLogin(openid)

        } catch (error) {
          console.error('登录错误:', error)
          uni.showToast({
            title: error.message || '登录失败，请重试',
            icon: 'none'
          })
        } finally {
          this.isLoggingIn = false
        }
      },
      // 封装微信登录
      wxLogin() {
        return new Promise((resolve, reject) => {
          uni.login({
            success: (res) => resolve(res),
            fail: (err) => reject(err)
          })
        })
      },
      // 微信登录处理
      async wechatLogin(openid) {
        try {
          await this.$store.dispatch('WechatLogin', openid)
          
          // 检查是否绑定微信
          const checkRes = await checkBindWechat(openid)
          if (!checkRes.data) {
            await bindWechat(openid)
          }

          this.loginSuccess()
        } catch (error) {
          throw new Error('微信登录失败：' + error.message)
        }
      },
      // 登录成功后，处理函数
      loginSuccess(result) {
        // 设置用户信息
        this.$store.dispatch('GetInfo').then(res => {
           // 登录成功后，获取保存的重定向页面
          const redirectPage = this.$store.state.user.redirectPage
          if (redirectPage) {
            // 跳转到保存的页面
            this.$tab.reLaunch(redirectPage)
          } else {
            this.$tab.reLaunch('/pages/index')
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  page {
    background-color: #ffffff;
  }
  .login-btn-bar {
	  /deep/ .u-btn {
		  height: 90rpx!important;
		  line-height: 90rpx!important;
		  font-size: 32rpx!important;
		  width: 100% !important;
	  }
  }

  .normal-login-container {
    width: 100%;

    .logo-content {
      width: 100%;
      font-size: 21px;
      text-align: center;
      padding-top: 20%;
		.logo-wrap{
			width: 160rpx;
			height: 160rpx;
			margin: 0 auto;
			border-radius: 16rpx;
			background-color: #FFF;
			display: flex;
			align-items: center;
			justify-content: center;
			box-shadow: 0 0 12rpx 0 var(--tai-border-color);
		}
      image {
        border-radius: 4px;
      }
    }
	
	/deep/ .u-checkbox__icon-wrap {
		height: 32rpx!important;
		width: 32rpx!important;
	}

    .login-form-content {
      text-align: center;
      margin: 20px auto;
      margin-top: 20%;
      width: 80%;

      .input-item {
        margin: 20px auto;
        background-color: #f5f6f7;
        height: 45px;
        border-radius: 20px;

        .icon {
          font-size: 38rpx;
          margin-left: 10px;
          color: #999;
        }

        .input {
          width: 100%;
          font-size: 14px;
          line-height: 20px;
          text-align: left;
          padding-left: 15px;
        }

      }

      .login-btn {
        margin-top: 40px;
        height: 45px;
      }
      
      .reg {
        margin-top: 15px;
      }
      
      .xieyi {
        color: #333;
        // margin-top: 20px;
		font-size: 24rpx;
		line-height: 24rpx;
      }
      
      .login-code {
        height: 38px;
        float: right;
      
        .login-code-img {
          height: 38px;
          position: absolute;
          margin-left: 10px;
          width: 200rpx;
        }
      }
    }
  }

</style>
